<?php
/**
 *  NevuxBB - Free Forum Software
 *  Copyright (C) 2008, 2010 NevuxBB (No one specific author)
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * View Forum
 * File: viewforum.php
 * Purpose: Showing all topics within a forum
 * Todo: Add improvements
 *
 */
				
require('system/files/global.php');

// start the initalisation of the main page (forum page)
if(isset($_GET['id']) && is_numeric($_GET['id'])) {
	// safe
	$sql = "SELECT COUNT(forum_id) AS `forum`, `forum_type` FROM `nbb_forums` WHERE `forum_id` = '" . Db_Abstraction::clean($_GET['id']) . "' GROUP BY forum_id";
	$result = Db_Abstraction::fetch_array($sql);
	
	if($result['forum'] < 1 || $result['forum_type'] != (1 || 2)) {
		// produce the error, render the error page
		// set title
		$core_template_system->setvar('page_title', $forum_info['forum_name'] . ' Redirecting');
			
		// show the header loaded
		$core_template_system->pparse();
		
		// include the language file for this page
		$core_lang_system->reset();
		$core_lang_system->add_file('view_forum');
			
		// set the error page variables
		$core_template_system->setvar(array('back_url' 		=> 'index.php',
											'error_message' => $core_lang_system->get_var('F_NO_EXIST', 3),
											'error' 	    => $core_lang_system->get_var('F_ERROR', 3),
											'breadcrumb' 	=> $core_nav_system->generateNav(
													array('settings'    => array('level_down' => false,
														  'main_class' 	=> 'menu'),
									  					  'information' => array('home' => array('data' => array(1 => 'Home',
																							 					 2 => 1)))))));
		
		// produce the error page
		$core_template_system->newTemplate(BASE_PATH . '/templates/' . ForumSettings::getCurrentTemplate() . '/error.html');
		$core_template_system->pparse();
	} elseif($result['forum_type'] == 3) {
		// exists but is a redirecting forum
		$sql = "SELECT * FROM `nbb_forums` WHERE `forum_id` = '" . Db_Abstraction::clean($_GET['id']) . "' LIMIT 1";
		$forum_info = Db_Abstraction::fetch_array($sql);
		
		// set title
		$core_template_system->setvar('page_title', $forum_info['forum_name'] . ' Redirecting');
		
		// show the header loaded
		$core_template_system->pparse();
		
		// include the language file for this page
		$core_lang_system->reset();
		$core_lang_system->add_file('view_forum');
		
		// begin the generation of the navigation system here
		$navigation_menu_parts = array('settings'     => array('level_down' => false,
															   'main_class' => 'menu'),
									   'information'  => array('home'   => array('data' => array(1 => 'Home',
																							  	 2 => 1)),
														 	  'forums' => array('data' => array(1 => $forum_info['forum_name'],
																								 2 => 1,
																					 			 3 => array('forum_id' => $forum_info['forum_id'])
																								 ))));

		// now we have the menu bar created, generate the warning page
		// this page is not forum specific but redirecting url specific
		$core_template_system->newTemplate(BASE_PATH . '/templates/' . ForumSettings::getCurrentTemplate() . '/warning.html');
		
		// do we want to add a thumbnial?
		if(GlobalSettings::getSetting('stw_enabled') == 1) {
			// we do want thumbnails
			require(BASE_PATH . '/system/classes/webthumbnail_class.php');
			$thumb = new WebThumbnail;
			
			// execute and return thumbnail info
			$thumb_cont = $thumb->get_thumbnail($forum_info['forum_url'], 'xlg');
			
			// did it work?
			if($thumb_cont !== false) {
				// did work
				$core_template_system->setvar(array('thumb_enabled' => true,
													'thumb_url'     => $thumb_cont,
													'warning_message' => $core_lang_system->get_var('WARN_URL_MESSAGE_T', 4)));
			}
		} else {
			// set non-thumbnail message
			$core_template_system->setvar(array('warning_message' => $core_lang_system->get_var('WARN_URL_MESSAGE', 4)));
		}
		
		// add some variables
		$core_template_system->setvar(array('warning_title'	  => $core_lang_system->get_var('WARNING_T', 4),
											'external_url'	  => $forum_info['forum_url'],
											'breadcrumb'	  => $core_nav_system->generateNav($navigation_menu_parts)));
			
		// parse and present the page
		$core_template_system->pparse();
	} else {
		// exists, continue normally
		// retrieve forum information
		$sql = "SELECT * FROM `nbb_forums` WHERE `forum_id` = '" . Db_Abstraction::clean($_GET['id']) . "' LIMIT 1";
		$forum_info = Db_Abstraction::fetch_array($sql);
		
		// set title
		$core_template_system->setvar('page_title', $forum_info['forum_name'] . ' Forum');
		
		// show the header loaded
		$core_template_system->pparse();
		
		// include the language file for this page
		$core_lang_system->reset();
		$core_lang_system->add_file('view_forum');
		
		// begin the generation of the navigation system here
		$navigation_menu_parts = array('settings'    => array('level_down' => false,
															  'main_class' => 'menu'),
									   'information' => array('home' => array('data' => array(1 => 'Home',
																							  2 => 1))));
		// startup the forum generation class
		include(BASE_PATH . '/system/classes/lite/langcore_lite_class.php');
		include(BASE_PATH . '/system/classes/pagination_class.php');
		include(BASE_PATH . '/system/classes/generateforums_class.php');
		
		// startup classes
		$forums = new generate_forums;
		$pagination_system = new pagination;
		
		// lets retrieve our forum info
		$forums->set_data('1', Db_Abstraction::clean($_GET['id']));
		$forums->get_forum_data();
		$forums->get_stats_array();
		$forums->get_latest_posts_array();
				
		// is this a subforum?
		if($forum_info['forum_type'] == 2) {
			// this is a subforum 
			// what's the parent forum?
			$sub_sql = "SELECT `forum_name`, `forum_id` FROM `nbb_forums` WHERE `forum_id` = '" . $forum_info['forum_parent'] . "'";
			$sub_result = Db_Abstraction::fetch_array($sub_sql);
			
			$navigation_menu_parts['information']['subforum'] = array('data' => array(1 => $sub_result['forum_name'],
																				  	  2 => 1,
																					  3 => array('forum_id' => $sub_result['forum_id'])));
		} else {
			// are there any subforums?
			$sub_sql = "SELECT COUNT(forum_id) AS `total` FROM `nbb_forums` WHERE `forum_parent` = '" . Db_Abstraction::clean($_GET['id']) . "'";
			$sub_result = Db_Abstraction::fetch_array($sub_sql);
		
			if($forum_info['forum_type'] == 1 && $sub_result['total']) {
				// there are some subforums
				// retrieve the subforums from the database
				
				// get the data
				$loop = $forums->generate_forum_list();
				
				// set some variables
				$core_template_system->setvar(array('parent_forum_name' => $forum_info['forum_name'],
													'forum' 			=> $forums->get_lang_var('FORUM', 3),
													'l_post' 			=> $forums->get_lang_var('L_POST', 3),
													'replies'			=> $forums->get_lang_var('REPLIES', 3),
													'topics_posts'		=> $forums->get_lang_var('TOPICS_POSTS', 3)));
				
				// start the forums loop
				$core_template_system->setloop('parent_subforums', $loop);
				
				// let the system know we have subforums
				$core_template_system->setvar('is_subforums', true);
			}
		}
		
		// start pagination
		$pagination_system->setvar(Db_Abstraction::clean($_GET['page']), $forums->get_specific_stats_array($_GET['id'], 'topics'), $_GET['id'], 1);
		
		// load the topics
		$topics_sql = "SELECT t.topic_forum_id, t.topic_sticky, t.topic_locked, t.topic_views, t.topic_id, t.topic_title, t.topic_subject, t.topic_prefix, UNIX_TIMESTAMP(t.topic_lupdate) AS `unix_time`, u.user_id, u.user_name, COUNT(p.post_id) AS 'posts' FROM nbb_topics t LEFT JOIN nbb_users u ON t.topic_starter = u.user_id LEFT JOIN nbb_posts p ON t.topic_id = p.topic_id WHERE t.topic_forum_id = '" . Db_Abstraction::clean($_GET['id']) . "' GROUP BY t.topic_id ORDER BY t.topic_sticky DESC, t.topic_lupdate DESC LIMIT " . $pagination_system->getLimit();
		$topics_result = Db_Abstraction::query($topics_sql);
		
		$topics = array(); $i = 0; $read_unread = array();
		while($row = DB_Abstraction::fetch_assoc($topics_result)) {
			// does this topic have new posts?
			if(CoreUserSystem::isLoggedIn()) {
				if(isset($_SESSION['User']['tracking_table'][$row['topic_forum_id']]['marked_read']) && $_SESSION['User']['tracking_table'][$row['forum_id']]['marked_read'] > $row['unix_time']) {
					// no new posts
					$new_posts = false;
				} else {
					// marked read hasn't been set
					// is the last login timestamp more than last post
					if($_SESSION['User']['user_la1'] > $row['unix_time']) {
						// no new posts
						$new_posts = false;
						$read_unread['read'][$i] = true;
					} else {
						// have we already "read" this topic?
						if(isset($_SESSION['User']['tracking_table'][$row['topic_forum_id']][$row['topic_id']]) && $_SESSION['User']['tracking_table'][$row['topic_forum_id']][$row['topic_id']] > $row['unix_time']) {
							// no new posts
							$new_posts = false;
							$read_unread['read'][$i] = true;
						} else {
							// there is
							$new_posts = true;
							$read_unread['unread'][$i] = true;
						}
					}
				}
			} else {
				// we're not keeping track of guests, don't need or want to
				$new_posts = false;
				$read_unread['read'][$i] = true;
			}
			
			// set the array
			$topics[$i] = array('topic_id' 		  => $row['topic_id'],
								'topic_title'     => $row['topic_title'],
								'topic_subject'   => $row['topic_subject'],
								'topic_prefix' 	  => $row['topic_prefix'],
								'topic_views' 	  => $row['topic_views'],
								'topic_sticky'    => $row['topic_sticky'],
								'topic_locked'    => $row['topic_locked'],
								'author' 		  => $row['user_name'],
								'new_posts'       => $new_posts,
								'topic_url' 	  => urlSystem::viewURL(3, array('topic_id' => $row['topic_id'])),
								'total_replies'   => ($row['posts'] - 1),
								'last_post_ptime' => date('G:ia', $row['unix_time']),
								'last_post_date'  => date('d/m/Y', $row['unix_time']),
								'w_at' 			  => $core_lang_system->get_var('AT', 4),
								'author_url' 	  => urlSystem::viewURL(2, array('user_id'   => $row['user_id'],
																				 'user_name' => $row['user_name'])));
			
			$i++;
		}
		
		// do we need to update the forum index?
		if(count($read_unread['read']) == $i && CoreUserSystem::isLoggedIn()) {
			// no more unread posts, set as read
			$_SESSION['User']['tracking_table'][$_GET['id']]['marked_read'] = time();
		}
		
		// are there any topics to show?
		if($i > 0) {
			// some results in the array
			$core_template_system->setloop('loop', $topics);
		} else {
			// no results returned, empty forum or stats out of sync?
			$core_template_system->setvar(array('no_topics'   => true,
												'err_message' => 'No topics!'));
		}
		
		// render the navigation page
		$navigation_menu_parts['information']['forums'] = array('data' => array(1 => $forum_info['forum_name'],
																				2 => 1,
																				3 => array('forum_id' => $forum_info['forum_id'])));
		
		// add some language variables
		$core_template_system->setvar(array('show_pagination' => $pagination_system->displayPagination(),
											'forum_name' 	  => $forum_info['forum_name'],
											'forum_id' 		  => $forum_info['forum_id'],
											'topic_title' 	  => $core_lang_system->get_var('W_TTITLE', 3),
											'views' 		  => $core_lang_system->get_var('W_VIEWS', 3),
											'replies'		  => $forums->get_lang_var('REPLIES', 3),
											'last_post' 	  => $core_lang_system->get_var('W_LPOST', 3),
											'Author' 		  => $core_lang_system->get_var('W_AUTHOR', 3),
											'breadcrumb' 	  => $core_nav_system->generateNav($navigation_menu_parts)));
		
		// render the page
		$core_template_system->newTemplate(BASE_PATH . '/templates/' . ForumSettings::getCurrentTemplate() . '/viewforum.html');
		$core_template_system->pparse();
	}
} else {
	// produce the error, render the error page
	// set title
	$core_template_system->setvar('page_title', $forum_info['forum_name'] . ' Redirecting');
		
	// show the header loaded
	$core_template_system->pparse();
	
	// include the language file for this page
	$core_lang_system->reset();
	$core_lang_system->add_file('view_forum');
		
	// set the error page variables
	$core_template_system->setvar(array('back_url' 		=> 'index.php',
										'error_message' => $core_lang_system->get_var('F_NO_EXIST', 3),
										'error' 		=> $core_lang_system->get_var('F_ERROR', 3)));
	
	// produce the error page
	$core_template_system->newTemplate(BASE_PATH . '/templates/' . ForumSettings::getCurrentTemplate() . '/error.html');
	$core_template_system->pparse();
}

// load the footer
require('system/files/footer.php');
?>